package com.omg.api.handle;

import java.util.List;

import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.omg.api.argument.Argument;
import com.omg.api.argument.FeedArgument;
import com.omg.api.result.Result;
import com.omg.api.result.body.FeedBody;
import com.omg.api.result.header.FeedHeader;
import com.omg.constant.ResponseCode;
import com.omg.persistence.dao.lifepoint.entity.LPActivity;
import com.omg.persistence.dao.lifepoint.entity.LPUser;
import com.omg.persistence.delegate.lifepoint.LPActivityDelegate;
import com.omg.persistence.delegate.lifepoint.LPCommentDelegate;
import com.omg.persistence.delegate.lifepoint.LPUserDelegate;

/**
 * 
 * @author xiazhiquan
 * 
 *         May 29, 2011
 */
public class FeedHandler extends Handler {

	private static final Logger LOG = Logger.getLogger(FeedHandler.class
			.getName());

	private static FeedHandler instance = null;

	static {
		instance = new FeedHandler();
	}

	public static FeedHandler getInstance() {
		return instance;
	}

	public String handle(Argument argument) throws Exception {

		String userid = ((FeedArgument) argument).getUserid();

		List<LPActivity> activities = LPActivityDelegate.getInstance()
				.getFeedsByUserid(userid);
		for (LPActivity activity_info : activities) {
			LPUser owner_info = LPUserDelegate.getInstance().getLPUserByUserid(
					activity_info.getOwner());
			owner_info.setPasswd(null);
			owner_info.setSid(null);
			owner_info.setVersion(null);
			activity_info.setOwner_info(owner_info);
			activity_info.setOwner(null);
			activity_info
					.setComment_total(LPCommentDelegate.getInstance()
							.getCommentTotalByActivityId(
									activity_info.getActivityid()));
		}

		return getJson(activities);
	}

	private final String getJson(List<LPActivity> activities) throws Exception {
		try {

			// construct result
			Result result = new Result();

			// header
			FeedHeader header = new FeedHeader();
			header.setRespcode(ResponseCode.AP_E_Succ);
			result.setHeader(header);

			// body
			FeedBody body = new FeedBody();
			body.setActivities(activities);
			result.setBody(body);

			return new Gson().toJson(result);
		} catch (Exception e) {
			e.printStackTrace();
			String errorMsg = e.getMessage();
			LOG.error(errorMsg, e);
			throw new Exception(""
					+ (errorMsg != null && !errorMsg.isEmpty() ? errorMsg
							: ResponseCode.AP_E_Info_UnkownError));
		}
	}

}
